package software.lib.util;

import org.neo4j.driver.v1.Value;
import software.lib.service.LshCaller;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Wang on 2017/6/2.
 */
public class NeoSplit {
    public static void main(String[] args){
        splitLanguages();
    }

    public static void splitTags(){
        try(NeoDriver driver = new NeoDriver()){
            driver.query("match (g:gig)-[]-(t:tag) return ID(g) AS gid,split(t.name,'|') AS tgs").list()
                    .parallelStream().forEach(record -> {
                int gid = record.get("gid").asInt();
                record.get("tgs").asList(Value::asString).parallelStream().forEach(tg -> {
                    driver.query("start g=node("+gid+") " +
                            "merge (tg:Tag {name:'"+tg+"'}) " +
                            "merge (tg)-[r:of]->(g) " +
                            "return r");
                });
            });
        }
    }

    static final Pattern langPattern = Pattern.compile("([^\\(]+)\\(([^\\)]+)\\)");

    public static void splitLanguages(){
        try(NeoDriver driver = new NeoDriver()){
            driver.query("match (s:seller)-[]-(t:language) return ID(s) AS sid,split(t.name,'|') AS langs").list()
                    .parallelStream().forEach(record -> {
                int sid = record.get("sid").asInt();
                record.get("langs").asList(Value::asString).parallelStream().forEach(lang -> {
                   if(Arrays.stream(LshCaller.languageList).parallel().anyMatch(s -> lang.contains(s))){
                       Matcher matcher = langPattern.matcher(lang);
                       if(matcher.matches()){
                           String langName = matcher.group(1);
                           String langDesc = matcher.group(2);

                           driver.query("start s=node("+sid+") " +
                                   "merge (lg:Language {name:'"+langName+"',description:'"+langDesc+"'}) " +
                                   "merge (lg)-[r:speak]->(s) " +
                                   "return r");
                       }
                   }

                });
            });
        }
    }



}
